/**
 * 功能：
 * 1. 传入 items 属性，使 TableFilterForm 可配置
 * 2. 传入 onSearch、onReset 属性，监听查询按钮、重置按钮点击事件
 * 3. 暴露getForm()方法，给调用该组件的父组件定义ref，通过ref使用form
 */
import React, {
  useState,
  useEffect,
  useImperativeHandle,
  forwardRef,
} from "react"
import styles from "./HcpTableFilterNew.module.less"
import { Form, Button } from "antd"
import { DoubleRightOutlined } from "@ant-design/icons"
import { debounce } from "lodash"
import hcpUtils from "@/utils/hcpUtils"

const LabelText = ({ text }) => (
  <div
    style={{
      display: "inline-block",
      // width: 70,
    }}
  >
    {text}
  </div>
)

let HcpTableFilterNew = (
  { form, items, onSearch, restProps, resetClick, initialValues, loading,showCollapsed,hiddenOverflow },
  ref
) => {
  // const [form] = Form.useForm();
  items.forEach((v, k) => {
    if (v == null) {
      items.splice(k, 1)
    }
  })
  const oldFormFoldHeight = items.length > 2 ? 98 : 49
  const formItemGutter = 60
  const [collapsed, setCollapsed] = useState(false)
  const [formFoldHeight, setFormFoldHeight] = useState(oldFormFoldHeight)
  const [foldButtonVisible, setFoldButtonVisible] = useState(true)
  const [innerWidth, setInnerWidth] = useState(window.innerWidth)
  // useImperativeHandle(ref, () => ({
  //   getForm: () => {
  //     return form;
  //   }
  // }));
  window.onresize = () => {
    setInnerWidth(window.innerWidth)
    if (items.length <= 2) {
      if (innerWidth > 1138) {
        setFormFoldHeight(49)
      } else {
        setFormFoldHeight(98)
      }
    }
  }

  useEffect(() => {
      let offsetHeight = showCollapsed ? 205 :105;
    const handleResize = () => {
      const FORM_DOM = document.querySelector(
        "#table-filter > form .items__container"
      )
      if (FORM_DOM.offsetHeight > offsetHeight) {
        setFoldButtonVisible(true)
        setCollapsed(true)
      } else {
        setFoldButtonVisible(false)
        setCollapsed(false)
      }
    }
    handleResize()
    const resizeDebounced = debounce(handleResize, 300)
    hcpUtils.addEvent(window, "resize", resizeDebounced)
    return () => {
      hcpUtils.removeEvent(window, "resize", resizeDebounced)
    }
  }, [])

  // 监听查询按钮点击
  const handleSearch = (values) => {
    onSearch(values)
  }

  // 监听重置按钮点击
  const handleReset = () => {
    let keys = Object.keys(form.getFieldValue());
    form.resetFields(keys)
    resetClick && resetClick()
    // if (resetClick && resetClick()) {
    //   onSearch && onSearch(form.getFieldValue())
    // }
  }

  // 渲染表单项
  const renderFormItems = () => {
    return items.map((item) => {
      const { label, style, field, component, options, required=false,requiredTeXt, ...rest } = item
      // console.log(item)
      //限定所有输入框长度限定为50个字符
      let newComponent = component
      if (
        component &&
        component.props &&
        component.props.type == "text" &&
        !component.props.maxLength
      ) {
        newComponent = React.cloneElement(component, { maxLength: 50 })
      }
      return label ? (
        <Form.Item
          rules={ required ? [{ required: true, message: requiredTeXt  }] :[]}
          style={{
            marginRight: 0,
            paddingLeft: formItemGutter / 2,
            paddingRight: formItemGutter / 2,
            ...style,
          }}
          label={<LabelText text={label} />}
          key={field}
          name={field}
          {...options}
          {...rest}
        >
          {newComponent}
        </Form.Item>
      ) : (
        <Form.Item
          style={{
            marginRight: 0,
            paddingLeft: formItemGutter / 2,
            paddingRight: formItemGutter / 2,
            width: "364px",
            ...style,
          }}
          key={field}
        >
          {newComponent}
        </Form.Item>
      )
    })
  }

  // 渲染按钮组
  const renderButtons = () => {
    return (
      <Form.Item
        style={{
          float: "right",
          // marginLeft: foldButtonVisible
          //   ? -(formItemGutter / 2)
          //   : formItemGutter / 2,
          // paddingRight: formItemGutter / 2,
          marginRight: "0",
          marginLeft: 0,
          zIndex: 1,
          marginTop: items.length > 2 && collapsed ? "52px" : "0",
          width: items.length > 2 && collapsed ? "210px" : "auto",
        }}
      >
        <Button
          style={{ marginRight: 10, marginLeft: -20 }}
          loading={loading}
          type="primary"
          htmlType="submit"
        >
          查询
        </Button>
        <Button onClick={handleReset}>重置</Button>
        {foldButtonVisible && (
          <Button
            style={{ marginLeft: 20, padding: 0 }}
            type="link"
            onClick={() => setCollapsed(!collapsed)}
          >
            {collapsed ? "展开" : "收起"}
            <DoubleRightOutlined rotate={collapsed ? 90 : -90} />
          </Button>
        )}
      </Form.Item>
    )
  }

  return (
    <div {...restProps} className="hcp-table-filter" id="table-filter" style={{ width: "100%" }}>
      <Form
        form={form}
        initialValues={initialValues}
        style={{
          marginLeft: -(formItemGutter / 2),
          marginRight: -(formItemGutter / 2),
          // overflow: "hidden",
          display: "block",
          width: "calc(100% + 30px)",
          ...(collapsed ? { height: formFoldHeight } : null),
          ...(hiddenOverflow ? null : { overflow: "hidden" }),
        }}
        layout="inline"
        noValidate
        autoComplete="off"
        onFinish={handleSearch}
      //className={styles.hcp__table__form}
      >
        <div
          style={
            collapsed
              ? {
                display: "flex",
                justifyContent: "space-between",
              }
              : {}
          }
        >
          <div className="items__container" style={{ display: "inline" }}>
            {renderFormItems()}
          </div>
          {collapsed ? <div>{renderButtons()}</div> : renderButtons()}
        </div>
      </Form>
    </div>
  )
}

HcpTableFilterNew = forwardRef(HcpTableFilterNew)

export default React.memo(HcpTableFilterNew)
